import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel,
  Divider,
  Alert,
  Tabs,
  Tab,
  Paper,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions
} from '@mui/material';
import {
  Save as SaveIcon,
  Business as BusinessIcon,
  Security as SecurityIcon,
  Storage as StorageIcon,
  Notifications as NotificationsIcon,
  Language as LanguageIcon,
  Palette as PaletteIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { PageHeader } from '@/components/common/PageHeader';
import { settingsService } from '@/services/settingsService';
import type { TenantSettings } from '@/types';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`settings-tabpanel-${index}`}
      aria-labelledby={`settings-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

const TenantSettingsPage: React.FC = () => {
  const queryClient = useQueryClient();
  const [currentTab, setCurrentTab] = useState(0);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [selectedSetting, setSelectedSetting] = useState<any>(null);

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors, isDirty }
  } = useForm({
    defaultValues: {
      tenantName: '',
      tenantDomain: '',
      maxUsers: 100,
      maxStorage: 1024,
      enableSso: false,
      enableAuditLog: true,
      timezone: 'Asia/Shanghai',
      language: 'zh-CN',
      theme: 'light'
    }
  });

  // 获取租户设置
  const { data: tenantSettings, isLoading } = useQuery({
    queryKey: ['tenant-settings'],
    queryFn: () => settingsService.getTenantSettings()
  });

  // 更新租户设置
  const updateSettingsMutation = useMutation({
    mutationFn: (data: any) => settingsService.updateTenantSettings(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tenant-settings'] });
    }
  });

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
  };

  const handleSaveSettings = (data: any) => {
    updateSettingsMutation.mutate(data);
  };

  React.useEffect(() => {
    if (tenantSettings) {
      reset(tenantSettings);
    }
  }, [tenantSettings, reset]);

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="租户设置"
        description="管理当前租户的配置信息和功能设置"
        action={
          <Button
            variant="contained"
            startIcon={<SaveIcon />}
            onClick={handleSubmit(handleSaveSettings)}
            disabled={!isDirty || updateSettingsMutation.isPending}
          >
            {updateSettingsMutation.isPending ? '保存中...' : '保存设置'}
          </Button>
        }
      />

      <Card>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={currentTab} onChange={handleTabChange}>
            <Tab 
              icon={<BusinessIcon />} 
              label="基本信息" 
              iconPosition="start"
            />
            <Tab 
              icon={<SecurityIcon />} 
              label="安全设置" 
              iconPosition="start"
            />
            <Tab 
              icon={<StorageIcon />} 
              label="存储配额" 
              iconPosition="start"
            />
            <Tab 
              icon={<NotificationsIcon />} 
              label="通知设置" 
              iconPosition="start"
            />
            <Tab 
              icon={<PaletteIcon />} 
              label="外观设置" 
              iconPosition="start"
            />
          </Tabs>
        </Box>

        {/* 基本信息 */}
        <TabPanel value={currentTab} index={0}>
          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <Controller
                name="tenantName"
                control={control}
                rules={{ required: '租户名称不能为空' }}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="租户名称"
                    fullWidth
                    error={!!errors.tenantName}
                    helperText={errors.tenantName?.message}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="tenantDomain"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="租户域名"
                    fullWidth
                    placeholder="example.com"
                    helperText="用于子域名访问和邮件配置"
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="description"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="租户描述"
                    fullWidth
                    multiline
                    rows={3}
                    placeholder="描述租户的业务范围和用途"
                  />
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="timezone"
                control={control}
                render={({ field }) => (
                  <FormControl fullWidth>
                    <InputLabel>时区</InputLabel>
                    <Select {...field} label="时区">
                      <MenuItem value="Asia/Shanghai">Asia/Shanghai (+08:00)</MenuItem>
                      <MenuItem value="UTC">UTC (+00:00)</MenuItem>
                      <MenuItem value="America/New_York">America/New_York (-05:00)</MenuItem>
                      <MenuItem value="Europe/London">Europe/London (+00:00)</MenuItem>
                    </Select>
                  </FormControl>
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="language"
                control={control}
                render={({ field }) => (
                  <FormControl fullWidth>
                    <InputLabel>默认语言</InputLabel>
                    <Select {...field} label="默认语言">
                      <MenuItem value="zh-CN">简体中文</MenuItem>
                      <MenuItem value="zh-TW">繁体中文</MenuItem>
                      <MenuItem value="en-US">English</MenuItem>
                      <MenuItem value="ja-JP">日本語</MenuItem>
                    </Select>
                  </FormControl>
                )}
              />
            </Grid>
          </Grid>
        </TabPanel>

        {/* 安全设置 */}
        <TabPanel value={currentTab} index={1}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Alert severity="info" sx={{ mb: 3 }}>
                安全设置影响整个租户的安全策略，请谨慎配置。
              </Alert>
            </Grid>
            <Grid item xs={12}>
              <Paper sx={{ p: 2 }}>
                <Typography variant="h6" sx={{ mb: 2 }}>认证设置</Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <Controller
                      name="enableSso"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="启用单点登录 (SSO)"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="enableTwoFactor"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="强制两步验证"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="enableAuditLog"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="启用审计日志"
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Paper>
            </Grid>
            <Grid item xs={12}>
              <Paper sx={{ p: 2 }}>
                <Typography variant="h6" sx={{ mb: 2 }}>密码策略</Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name="passwordMinLength"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="密码最小长度"
                          type="number"
                          fullWidth
                          inputProps={{ min: 6, max: 32 }}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name="passwordExpireDays"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="密码有效期（天）"
                          type="number"
                          fullWidth
                          inputProps={{ min: 0, max: 365 }}
                          helperText="0 表示永不过期"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="requireComplexPassword"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="要求复杂密码（包含大小写字母、数字和特殊字符）"
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Paper>
            </Grid>
          </Grid>
        </TabPanel>

        {/* 存储配额 */}
        <TabPanel value={currentTab} index={2}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Alert severity="warning" sx={{ mb: 3 }}>
                存储配额设置会影响租户下所有用户的存储限制。
              </Alert>
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="maxUsers"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="最大用户数"
                    type="number"
                    fullWidth
                    inputProps={{ min: 1 }}
                    helperText="租户可创建的最大用户数量"
                  />
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="maxOrganizations"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="最大组织数"
                    type="number"
                    fullWidth
                    inputProps={{ min: 1 }}
                    helperText="租户可创建的最大组织数量"
                  />
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="maxStorage"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="存储容量 (MB)"
                    type="number"
                    fullWidth
                    inputProps={{ min: 100 }}
                    helperText="租户总存储容量限制"
                  />
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="maxFileSize"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="单文件大小限制 (MB)"
                    type="number"
                    fullWidth
                    inputProps={{ min: 1, max: 100 }}
                    helperText="单个文件上传大小限制"
                  />
                )}
              />
            </Grid>
          </Grid>
        </TabPanel>

        {/* 通知设置 */}
        <TabPanel value={currentTab} index={3}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Paper sx={{ p: 2 }}>
                <Typography variant="h6" sx={{ mb: 2 }}>邮件通知</Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <Controller
                      name="enableEmailNotification"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="启用邮件通知"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name="smtpHost"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="SMTP 服务器"
                          fullWidth
                          placeholder="smtp.example.com"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name="smtpPort"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="SMTP 端口"
                          type="number"
                          fullWidth
                          placeholder="587"
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Paper>
            </Grid>
            <Grid item xs={12}>
              <Paper sx={{ p: 2 }}>
                <Typography variant="h6" sx={{ mb: 2 }}>系统通知</Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <Controller
                      name="notifyUserLogin"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="用户登录通知"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="notifyUserRegister"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="用户注册通知"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="notifySystemError"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="系统错误通知"
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Paper>
            </Grid>
          </Grid>
        </TabPanel>

        {/* 外观设置 */}
        <TabPanel value={currentTab} index={4}>
          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <Controller
                name="theme"
                control={control}
                render={({ field }) => (
                  <FormControl fullWidth>
                    <InputLabel>默认主题</InputLabel>
                    <Select {...field} label="默认主题">
                      <MenuItem value="light">浅色主题</MenuItem>
                      <MenuItem value="dark">深色主题</MenuItem>
                      <MenuItem value="auto">跟随系统</MenuItem>
                    </Select>
                  </FormControl>
                )}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <Controller
                name="primaryColor"
                control={control}
                render={({ field }) => (
                  <FormControl fullWidth>
                    <InputLabel>主色调</InputLabel>
                    <Select {...field} label="主色调">
                      <MenuItem value="blue">蓝色</MenuItem>
                      <MenuItem value="green">绿色</MenuItem>
                      <MenuItem value="purple">紫色</MenuItem>
                      <MenuItem value="orange">橙色</MenuItem>
                    </Select>
                  </FormControl>
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="customLogo"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="自定义 Logo URL"
                    fullWidth
                    placeholder="https://example.com/logo.png"
                    helperText="留空使用默认 Logo"
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="customFavicon"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label="自定义 Favicon URL"
                    fullWidth
                    placeholder="https://example.com/favicon.ico"
                    helperText="留空使用默认 Favicon"
                  />
                )}
              />
            </Grid>
          </Grid>
        </TabPanel>
      </Card>
    </Box>
  );
};

export default TenantSettingsPage;